import React, { useEffect, useRef, useState } from "react";
import "./HeroCom.css";
import axios from "axios";
import { useNavigate } from "react-router-dom";

export default function HeroCom() {
  //声明英雄数据的状态
  let [heros, setHeros] = useState([]);
  //使用 useRef
  let input = useRef();
  //声明关键字的状态
  let [keyword, setKeyword] = useState('');
  //定义状态
  let [isLoading, setIsLoading] = useState(false);

  //组件挂载完毕的操作
  useEffect(() => {
    //获取英雄数据
    let getHeros = async () => {
      //更新加载中状态
      setIsLoading(true);
      //清空英雄数据
      setHeros([]);
      //发送 AJAX 请求获取相关的英雄
      let { data } = await axios.get("http://api.xiaohigh.com/heros", {
        //设置查询字符串的
        params: {
          name_like: keyword,
        },
      });
      setIsLoading(false);
      //更新英雄的状态
      setHeros(data);
    };
    getHeros();
  }, [keyword]);

  //声明 search 函数
  let search = async () => {
    //获得 input 框的值
    let keyword = input.current.value;
    //更新 keyword 状态的值
    setKeyword(keyword);
  };

  //获取 navigate 函数 navigate(导航)
  let navigate = useNavigate();

  return (
    <div className="hero-container">
      <button className="btn btn-info" onClick={() => {
        navigate(1);
      }}>前进</button>
      <h2>欢迎来到王者荣耀</h2>
      <hr />
      <div className="form-section">
        <input type="text" ref={input} />
        <button onClick={search}>搜索</button>
      </div>
      <hr />
      <div className="hero-list">
        {/* 空状态提醒 */}
        {!isLoading && heros.length === 0 && <h3 style={{textAlign: 'center'}}>暂无数据</h3>}
        {/* 加载中.... */}
        {isLoading && <h3 style={{textAlign: 'center'}}>加载中...</h3>}
        {heros.map((item, index) => {
          return (
            <div className="hero-item" key={index}>
              <img
                width="100%"
                src={`http://cdn.xiaohigh.com${item.image}`}
                alt=""
                //绑定事件
                onClick={() => {
                  //跳转 params 传参跳转
                  // navigate(`/hero/${item.id}`);
                  //query 传参
                  // navigate(`/hero?hd=${item.id}`);
                  //state 传参
                  navigate('/hero', {
                    state: {
                      id: item.id
                    },
                    //替换模式
                    // replace: true
                  })
                }}
              />
              <div className="name">{item.name}</div>
            </div>
          );
        })}
      </div>
    </div>
  );
}
